package dmwr.repo.gae;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import dmwr.util.Executor;
import dmwr.util.Operation;

public final class Gae {
	private static final ThreadLocal<DatastoreService> DATASTORE_SERVICE = new ThreadLocal<DatastoreService>();
	private static final ThreadLocal<UserService> USER_SERVICE = new ThreadLocal<UserService>();
	private static final Executor TRANSACTOR = new Executor() {

		@Override
		public <T> T execute(Operation<T> op) {
			DatastoreService ds = null;
			UserService us = null;
			try {
				ds = DatastoreServiceFactory.getDatastoreService();
				DATASTORE_SERVICE.set(ds);
				us = UserServiceFactory.getUserService();
				USER_SERVICE.set(us);
				return op.execute();
			} catch (Exception e) {
				throw new RuntimeException(e);
			} finally {
				DATASTORE_SERVICE.set(null);
				USER_SERVICE.set(null);
			}
		}
	};

	private Gae() {
	}

	public static DatastoreService datastoreService() {
		return DATASTORE_SERVICE.get();
	}

	public static UserService userService() {
		return USER_SERVICE.get();
	}

	public static Executor transactor() {
		return TRANSACTOR;
	}
}
